<?php

namespace Common\Model;

use Think\Model;

/**
 * 帖子模型
 */
class TieModel extends Model {

    const NORMAL = 0;   // 帖子状态：正常
    const DELTEL = -1;  // 帖子状态：删除（冻结）
    const TOP = 1;      // 帖子是否顶置：顶置
    const NO_TOP = 0;   // 帖子是否顶置：不顶置
    const ELITE = 1;    // 帖子是否加精：加精
    const NO_ELITE = 0; // 帖子是否加精：不加精

    const ELITE_MARK = 'elite'; // 帖子过滤标志：精品

    const TIE_KEY = 'tie:';     // 帖子信息的缓存键名
    const CACHE_TIME = 36000;      // 帖子的缓存时间

    /**
     * 新增一条帖子数据
     * @param $data
     * @return mixed
     */
    public static function addData($data){
        return M('Tie')->add($data);
    }

    /**
     * 创建帖子
     * @param $data
     * @return bool|mixed
     */
    public static function createTie($data){
        $tid = self::addData($data);
        if(!$tid){
            return false;
        }
        BbsCountModel::update($data['bid'], 'tz');
        return $tid;
    }

    /**
     * 获取帖子信息[不包含帖子作者相关信息]
     * @param $tid
     * @param bool $add
     * @return mixed|null
     */
    public static function getTieById($tid, $add = true){
        if (!$tid) return null;
        $key = self::TIE_KEY.$tid;
        $result = S($key);
        if (!$result && $result = M('Tie')->find($tid)) {
            S($key, $result);
        }
        if ($result && $add && $addData = TieCountModel::get($tid)) {
            foreach ($addData as $k => $v) {
                $result[$k] += $v;
            }
        }
        return $result;
    }

    /**
     * 补充帖子内容
     * @param $tid
     * @param $html
     * @return mixed
     */
    public static function fix($tid, $html){
        $html = '<p class="faq-update-msg">'.date('Y-m-d H:i:s',time()).' &nbsp;<strong>Update：</strong></p>'.filterXss($html);
        $data = [
            'html' => ['exp', 'concat(`html`, "'.addslashes($html).'")'],
            'update' => time()
        ];
        if($result = M('Tie')->where(['id' => $tid])->save($data)){
            self::clearCache($tid);
        }
        return $result;
    }

    /**
     * 分页获取社区首页的帖子列表数据
     * @param $where
     * @param $p
     * @param $pcount
     * @return array|bool
     */
    public static function getTies($where, $p, $pcount){
        $count = M()->table(['wo_tie' => 't'])->where($where)->count();
        $field = 't.id,t.title,t.html,t.cid,t.top,t.elite,t.reply,t.update,t.visit,t.uid,u.nick,u.avatar';
        $list = $count ? M()->table(['wo_tie' => 't', 'wo_user' => 'u'])->where($where)->where('t.uid = u.id')->field($field)->order('t.top desc,t.`update` desc')->page($p.','.$pcount)->select() : [];
        return [
            'count' => $count,
            'list' => $list
        ];
    }

    /**
     * 更新帖子的信息（如：删除/精华/顶置）
     * @param $tid
     * @param $data
     * @return bool
     */
    public static function update($tid, $data){
        if($result = M('Tie')->where(['id' => $tid])->save($data)){
            self::clearCache($tid);
        }
        return true;
    }

    /**
     * 创建回复之后更新帖子的更新时间和回复数
     * @param $tid
     * @return bool
     */
    public static function reply($tid){
        $data = [
            'update' => time(),
            'reply' => ['exp', ' reply + 1']
        ];
        return self::update($tid, $data);
    }

    /**
     * 获取社区中当前设为顶置的帖子数目
     * @param $bid
     * @return mixed
     */
    public static function getTopCount($bid){
        return M('Tie')->where(['bid' => $bid, 'top' => self::TOP])->count();
    }

    public static function clearCache($tid){
        $key = self::TIE_KEY.$tid;
        S($key, null);
    }

    /**
     * ///////////////////////////////////////////////////////////////////////
     * ///////////////////////////////////////////////////////////////////////
     */

    /**
     * 获取精品帖子列表
     * @param $bid
     * @param $p
     * @param $pcount
     * @return array
     */
    public static function getEliteList($bid, $p, $pcount){
        $count = M('Tie')->where(array('bid' => $bid, 'elite' => self::ELITE, 'status' => self::NORMAL))->count();
        $list = $count ? M()->table(array('wo_tie' => 't', 'wo_user' => 'u'))->where(array('t.bid' => $bid, 't.elite' => self::ELITE, 't.status' => self::NORMAL))->where('t.uid = u.id')->field('t.id,t.title,t.html,t.top,t.elite,t.reply,t.update,t.uid,u.nick')->order('t.top desc,t.`update` desc')->page($p.','.$pcount)->select() : array();
        $res = array('count' => $count, 'list' => $list);
        return $res;
    }

}